﻿using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command.RoleCommand;
using B.S.DataBase.MyRead.API.DTOs;
using MediatR;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.RoleCommandHandler
{
    /// <summary>
    /// /通过角色ID查询用户名称
    /// </summary>
    public class GetUserNameRoleidCommandHandler : IRequestHandler<GetUserNameRoleidCommand, APIResult<List<UserNameDTOs>>>
    {
        private readonly IBaseRepository<User> userRepos;
        private readonly IBaseRepository<Role> roleRepos;
        private readonly IBaseRepository<UserRole> userroleRepos;

        public GetUserNameRoleidCommandHandler(IBaseRepository<User> userRepos, IBaseRepository<Role> roleRepos, IBaseRepository<UserRole> userroleRepos
            )
        {
            this.userRepos = userRepos;
            this.roleRepos = roleRepos;
            this.userroleRepos = userroleRepos;
        }

        /// <summary>
        /// 通过角色ID查询用户名称
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<List<UserNameDTOs>>> Handle(GetUserNameRoleidCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<UserNameDTOs>> result = new APIResult<List<UserNameDTOs>>();
            var list = from a in userRepos.GetAll().Result
                       join b in userroleRepos.GetAll().Result on a.UserId equals b.UserId
                       join c in roleRepos.GetAll().Result on b.RoleId equals c.RoleId
                       where b.RoleId == request.RoleId
                       select new UserNameDTOs
                       {
                           DepId = a.DepId,
                           UserRoleId = b.UserRoleId,
                           NickName = a.NickName,
                           UserName = a.UserName,
                           RoleId = b.RoleId,
                           UserId = a.UserId,
                           RoleName = c.RoleName
                       };
            if (list != null)
            {
                result.Code = APIEnum.查询成功;
                result.Msg = APIEnum.查询成功.ToString();
                result.data = list.ToList();
            }
            else
            {
                result.Code = APIEnum.查询失败;
                result.Msg = APIEnum.查询失败.ToString();
                result.data = list.ToList();
            }
            return Task.FromResult(result);
        }
    }
}
